import java.util.Arrays;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * Author:  LiuTao
 * Version: 1.0
 * Date:    2023-09-20  18:19
 */
public class MyArrayList implements IList{
    public int[] elem;
    public int usedSiza;
    public static final int DEFAULT_SIZE = 10;
    public MyArrayList() {
        this.elem = new int[DEFAULT_SIZE];
    }

    public MyArrayList(int capacity) {
        this.elem = new int[capacity];
    }
    //在数组最后插入元素
    @Override
    public void add(int data) {
        checkCapacity();
        this.elem[this.usedSiza] = data;
        this.usedSiza++;
    }
    //在数组指定位置中插入元素
    @Override
    public void add(int pos, int data) {
        checkCapacity();
        for(int i = usedSiza-1; i >= pos; i--) {
            //1 2 3 4 5 0
            //0 1 2 3 4 5
            elem[i+1] = elem[i];
        }
        elem[pos] = data;
        usedSiza++;
    }
    // 判定是否包含某个元素
    @Override
    public boolean contains(int toFind) {
        for(int i = 0; i < usedSiza; i++) {
            if(elem[i] == toFind) {
                return true;
            }
        }
        return false;
    }
    // 查找某个元素对应的位置
    @Override
    public int indexOf(int toFind) {
        for(int i = 0; i < usedSiza; i++) {
            if(elem[i] == toFind) {
                return i;
            }
        }
        return -1;
    }
    // 获取  pos 位置的元素
    @Override
    public int get(int pos) {
        checkCapacity();
        return elem[pos];
    }
    //更改数组中指定位置的值
    @Override
    public void set(int pos, int value) {
        checkCapacity();
        this.elem[pos] = value;
    }
    //删除第一次出现的关键字key
    @Override
    public void remove(int toRemove) {
        int index = indexOf(toRemove);
        for(int i = index; i < usedSiza-1; i++) {
            if(index == elem[i]) {
                elem[i] = elem[i+1];
            }
        }
        usedSiza--;
    }
    //数组中存在值的长度
    @Override
    public int size() {
        return this.usedSiza;
    }
    //清空数组
    @Override
    public void clear() {
        this.usedSiza = 0;
    }
    //打印数组
    public void disply() {
        for(int i = 0; i < usedSiza; i++) {
            System.out.print(elem[i] + " ");
        }
    }
    //检查数组容量
    public boolean isFull() {
        return usedSiza == elem.length;
    }
    //判断是否对数组进行扩容
    public void checkCapacity() {
        if(isFull()) {
            elem = Arrays.copyOf(elem,elem.length*2);
        }
    }
    public boolean isEmpty() {
        return usedSiza == 0;
    }
    public void checkPosOnAdd(int pos) {
        if(pos < 0 || pos > usedSiza) {
            System.out.println("插入位置不合法");
        }
    }
}
